import tinymce from 'tinymce/tinymce'
import { save, saveTermContent } from '@/api'
import { getStrData2Save } from '@/utils/save'
import Socket from '@/utils/socket'
import store from '@/store'
import { sleep, updateDomain } from '@/utils/helpers'
import { getVariableTypeList } from '@/api/variable.js'
import { getAlgoList, editAlgo } from "@/api/computingConfig.js";

let timer = null, delay = 1.5 * 60 * 1000
tinymce.PluginManager.add('docSave', function (editor) {
  setTimeout(() => !timer && handleSave(), delay)
  const manualSave = () => handleSave(true) // 区分手动保存还是自动保存
  editor.addShortcut('ctrl+s', '保存', manualSave)

  return (
    editor.ui.registry.addMenuItem('docSave', {
      text: '保存',
      onAction: manualSave
    }),
    {
      getMetadata: function () {
        return {
          name: '保存',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})

export async function handleSave(isManual = false) {
  /** ------------------- 保存术语begin---------------------- */
  //是否调用接口保存
  if(store.state.xmleditor.docStatus==0 || store.state.xmleditor.docStatus==9){
    return;
  }
  if (store.getters.editContentType === 'block' && store.getters.entry === 'termblock') {
    const jsonContent = getStrData2Save()
    try {
      const res = await saveTermContent({ id: store.state.xmleditor?.editorConfig?.id, jsonContent }, !isManual)
      if (res.code === 200) {
        return successFn()
      }
      throw new Error()
    } catch (error) {
      return tinymce.activeEditor.notificationManager.open({ timeout: 1500, text: '保存失败!', type: 'error' })
    }
  }
  /** ------------------- 保存术语end---------------------- */

  const originalDocNo = store.state.xmleditor.originalEditorConfig.docNo
  const currentDocNo = store.state.xmleditor.editorConfig.docNo
  if (originalDocNo !== currentDocNo) {
    console.debug('切换到历史版本，不能保存内容')
    return
  }

  // 保存之前更新引用文件信息
  updateDomain()
  await sleep()
  // 保存变量列表
  // const variables = await getVariableTypeList();
  const variables = ['variable_string','variable_hide_string', 'variable_table', 'variable_chapt','table','variable_string_algo']
  const doc = tinymce.activeEditor.getDoc();
  let variablePushArr = new Set();
  variables.forEach(item => {
    const pageNodes = doc.querySelectorAll(`[data-type=${item}]`);
    if (pageNodes.length > 0) {
      pageNodes.forEach(el => {
        if (el.getAttribute('data-variable-id')) {
          variablePushArr.add(el.getAttribute('data-variable-id'))
        }
      })
    }
  })
  const { id } = store.state.xmleditor.editorConfig
  const { name } = store.state.xmleditor.docInfo
  //保存变量(模板)
  if (store.getters.editContentType === 'template') {
    const res = await getAlgoList({
      pageNum: 1,
      pageSize: 100,
    });
    if (res && res?.data?.list) {
      // 更新结果模板时，更新所有的算例结果模板变量
      if (name.includes("算例结果模板")) {
        const vars = [...variablePushArr];
        res.data.list.forEach(async (item) => {
          const params = { ...item }
          params.resultTemplateVars = await vars.map(item => {
            item = item.toString();
            return item;
          })
          editAlgo(params)
        })
        const varsStr = vars.toString();
        //数据缓存到本地
        localStorage.setItem("resultTemplateVariables",varsStr);
      } else {
        const templateId = await res?.data?.list.filter(item => {
          return item.templateId == id;
        })
        // 更新变量到模板中
        if (templateId && templateId.length > 0) {
          const params = { ...templateId[0] }
          const vars = [...variablePushArr];
          params.templateVars = await vars.map(item => {
            item = item.toString();
            return item;
          })
          editAlgo(params)
        }
      }
    }
  }


  const data = getStrData2Save()
  if (store.state.xmleditor.editorConfig.collaborate) {
    new Socket().send(data, successFn)
  } else {
    await save(data, !isManual)
    successFn()
  }
  function successFn() {
    clearTimeout(timer)
    timer = setTimeout(handleSave, delay)

    tinymce.activeEditor.save()
    if (!isManual) return // 自动保存的不进行提示
    tinymce.activeEditor.notificationManager.open({
      timeout: 1500,
      text: '保存成功!',
      type: 'success'
    })
  }
}
